<template>
  <div>
    <div class="cart">
      <table class="table">
        <thead>
          <tr>
            <th width="120">
              <input
                type="checkbox"
                v-model="flagAll"
                @change="chooseAll(flagAll)"
              />全选
            </th>
            <th width="400">商品信息</th>
            <th width="220">单价</th>
            <th width="180">数量</th>
            <th width="180">小计</th>
            <th width="140">操作</th>
          </tr>
        </thead>
        <!-- 有效商品 -->
        <tbody>
          <tr v-for="(item, index) in list" :key="index" align="center">
            <td>
              <input
                type="checkbox"
                @click="changeState(index)"
                v-model="item.selected"
              />
            </td>
            <td>
              <div class="goods">
                <RouterLink to="/"
                  ><img :src="item.picture" alt=""
                /></RouterLink>
                <div>
                  <p class="name ellipsis">
                    {{ item.name }}
                  </p>
                  <!-- 选择规格组件 -->
                  <CartSku></CartSku>
                </div>
              </div>
            </td>
            <td class="tc">
              <p>&yen;{{ item.price }}</p>
              <p>
                比加入时降价
                <span class="red">&yen;{{ item.nowPrice - item.price }}</span>
              </p>
            </td>
            <td class="tc">
              <NumBox
                :number="item.count"
                @cut="cut(index)"
                @add="add(index)"
              />
            </td>
            <td class="tc">
              <p class="f16 red">
                &yen;{{ (item.price * item.count).toFixed(2) }}
              </p>
            </td>
            <td class="tc">
              <p><a href="javascript:;">移入收藏夹</a></p>
              <p>
                <a class="green" href="javascript:;" @click="del(index)"
                  >删除</a
                >
              </p>
              <p><a href="javascript:;">找相似</a></p>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <!-- 操作栏 -->
    <div class="action">
      <div class="batch">
        <!-- <input type="checkbox" />全选 -->
        <a href="javascript:;" @click="chooseDel">删除商品</a>
        <a href="javascript:;">移入收藏夹</a>
        <a href="javascript:;">清空失效商品</a>
      </div>
      <div class="total">
        共 {{ $store.getters["Cart/cartNum"] }} 件商品，已选择
        {{ $store.getters["Cart/chooseNum"] }} 件，商品合计：
        <span class="red"
          >¥{{ $store.getters["Cart/allPrice"].toFixed(2) }}</span
        >
        <button class="btn" @click="$router.push('/member/settle')">
          下单结算
        </button>
      </div>
    </div>
  </div>
</template>

<script>
// 引入步进器
import NumBox from "@/components/utils/NumBox.vue";
// 引入规格
import CartSku from "@/components/Cart/CartSku.vue";
// 引入删除api
import { delCart } from "@/utils/Api/CartApi";
export default {
  components: {
    NumBox,
    CartSku,
  },
  data() {
    return {
      // 全选状态
      flagAll: false,
      // 请求来的购物车数据
      list: [],
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    // 数量减
    cut(index) {
      this.$store.commit("Cart/cutNum", index);
    },
    // 数量加
    add(index) {
      this.$store.commit("Cart/addNum", index);
    },
    // 全选
    chooseAll(flagAll) {
      this.$store.commit("Cart/chooseAll", flagAll);
    },
    // 删除
    del(index) {
      this.$confirm({
        text: "提示",
        title: "确认要删除吗？",
      }).then(
        async () => {
          // 判断是否登录
          if (
            this.$store.state.User.userInfo &&
            this.$store.state.User.userInfo.token
          ) {
            // 登录就调用删除接口
            let { data } = await delCart([this.list[index].skuId]);
            if (data.msg == "操作成功") {
              // 调用接口刷新页面
              this.getList();
              this.$message({
                text: "删除成功",
                type: "success",
              });
            }
          } else {
            // 没有登录就删除本地的
            this.$store.commit("Cart/del", index);
            this.$message({
              text: "删除成功",
              type: "success",
            });
          }
        },
        () => {
          this.$message({
            text: "取消删除",
            type: "error",
          });
        }
      );
    },
    // 选中删除
    chooseDel() {
      this.$confirm({
        text: "提示",
        title: "确认要批量删除吗？",
      }).then(
        async () => {
          // 判断是否登录
          if (
            this.$store.state.User.userInfo &&
            this.$store.state.User.userInfo.token
          ) {
            // 登录就调用删除接口
            let ids = [];
            this.list.forEach((item) => {
              if (item.selected) {
                ids.push(item.skuId);
              }
            });
            let { data } = await delCart(ids);
            if (data.msg == "操作成功") {
              // 调用接口刷新页面
              this.getList();
              this.$message({
                text: "删除成功",
                type: "success",
              });
            }
          } else {
            // 没有登录就删除本地的
            this.$store.commit("Cart/chooseDel");
            this.$message({
              text: "删除成功",
              type: "success",
            });
          }
        },
        () => {
          this.$message({
            text: "取消删除",
            type: "error",
          });
        }
      );
    },
    // 单个改变状态
    changeState(index) {
      this.$store.commit("Cart/changeState", index);
    },
    //判断登录之后请求购物车数据 进行赋值
    async getList() {
      if (
        this.$store.state.User.userInfo &&
        this.$store.state.User.userInfo.token
      ) {
        await this.$store.dispatch("Cart/asyncGetCart");
      }
      this.list = this.$store.state.Cart.list;
    },
  },

  // 监听反选
  watch: {
    list: {
      handler(val) {
        let len = val.filter((item) => item.selected).length;
        if (val.length == len && len != 0) {
          this.flagAll = true;
        } else {
          this.flagAll = false;
        }
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.table {
  background-color: white;
}
.btn {
  width: 180px;
  height: 50px;
  font-size: 16px;
  border-color: #27ba9b;
  background: #27ba9b;
  color: #fff;
  text-align: center;
  border: 1px solid transparent;
  border-radius: 4px;
  cursor: pointer;
}
.tc {
  text-align: center;
  .xtx-numbox {
    margin: 0 auto;
    width: 120px;
  }
}
.red {
  color: red;
}
.green {
  color: #27bb9a;
}
.f16 {
  font-size: 16px;
}
.goods {
  display: flex;
  align-items: center;
  img {
    width: 100px;
    height: 100px;
  }
  > div {
    width: 280px;
    font-size: 16px;
    padding-left: 10px;
    .attr {
      font-size: 14px;
      color: #999;
    }
  }
}
.action {
  display: flex;
  background: #fff;
  margin-top: 20px;
  height: 80px;
  align-items: center;
  font-size: 16px;
  justify-content: space-between;
  padding: 0 30px;
  .xtx-checkbox {
    color: #999;
  }
  .batch {
    a {
      margin-left: 20px;
    }
  }
  .red {
    font-size: 18px;
    margin-right: 20px;
    font-weight: bold;
  }
}
.tit {
  color: #666;
  font-size: 16px;
  font-weight: normal;
  line-height: 50px;
}
.xtx-cart-page {
  .cart {
    background: white;
    color: #666;
    table {
      border-spacing: 0;
      border-collapse: collapse;
      line-height: 24px;
      th,
      td {
        padding: 10px;
        border-bottom: 1px solid #f5f5f5;
        &:first-child {
          text-align: left;
          padding-left: 30px;
          color: #999;
        }
      }
      th {
        font-size: 16px;
        font-weight: normal;
        line-height: 50px;
      }
    }
  }
}
</style>
